package org.bookie.model.hibernate;

import java.util.GregorianCalendar;

import org.bookie.model.Bet;
import org.bookie.model.Category;
import org.bookie.model.Event;
import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.event.PostLoadEvent;
import org.hibernate.event.PostLoadEventListener;

public class CategoryPostLoadEventListener implements PostLoadEventListener {
	private static final long serialVersionUID = 1L;
	
	public void onPostLoad(PostLoadEvent event) {
		Object entity = event.getEntity();
		if(!entity.getClass().equals(Category.class)){
			return;
		}

		Category category = (Category)entity;
		Criteria criteria = event.getSession().createCriteria(Bet.class)
				.setProjection(Projections.distinct(
									Projections.projectionList()
										.add(Projections.rowCount())))
					.add(Restrictions.isNull("successfulOutcome"));
		addCriterias(criteria.createCriteria("event"), category.getId());
	
		Number count = (Number) criteria.uniqueResult();
		category.setBetCount(count.intValue());
		
		criteria = event.getSession().createCriteria(Event.class)
						.setProjection(Projections.distinct(
							Projections.projectionList()
								.add(Projections.rowCount())));
		criteria.createCriteria("bets")
			.add(Restrictions.isNull("successfulOutcome"));
		addCriterias(criteria, category.getId());
		count = (Number) criteria.uniqueResult();
		category.setEventCount(count.intValue());
		
		count = (Number) event.getSession()
					.createFilter(category.getEvents(), "select count(*)").list().get(0);
		category.setTotalEventCount(count.intValue());
	}
	
	private void addCriterias(Criteria criteria, Long id){
		criteria.add(Restrictions.gt("endDate", new GregorianCalendar().getTime()))
			.add(Restrictions.eq("state", Event.State.ACTIVE))
			.add(Restrictions.eq("category.id", id));
	}
}
